package com.mud.mudcommune.view.fragment;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.mud.mudcommune.R;
import com.mud.mudcommune.utils.LogUtils;
import com.mud.mudcommune.view.activity.FeedbackActivity;
import com.mud.mudcommune.view.activity.LoginActivity;
import com.mud.mudcommune.view.activity.RecodeBrowseActivity;
import com.mud.mudcommune.view.activity.SetupActivity;
import com.mud.mudcommune.view.fragment.twoLevel.AboutUsFragment;
import com.mud.mudcommune.view.fragment.twoLevel.MessCenterFragment;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.CropCircleTransformation;

import static android.app.Activity.RESULT_OK;

/**
 * A simple {@link Fragment} subclass.
 */
public class MineFragment extends Fragment implements View.OnClickListener {
    private static MineFragment fragment = new MineFragment();
    private LinearLayout servicePhone, recordLinear, feedbackLinear, checkVersion;
    private PopupWindow popupWindow = null;
    @BindView(R.id.login_icon)
    ImageView loginIcon;
    @BindView(R.id.login_relative1)
    RelativeLayout messCenter;
    @BindView(R.id.login_relative2)
    RelativeLayout colletionMine;
    @BindView(R.id.setting_login)
    ImageView setting;
    @BindView(R.id.Mine_Linear)
    LinearLayout linearLayout;
    @BindView(R.id.about_us)
    LinearLayout about_us;
    private static TextView username;
    private SystemBarTintManager tintManager;
    private static final int TAKE_PIC = 1;
    private static final int CHOICE_PIC = 2;
    private static final int CROP = 200;

    public static Fragment getInstance() {
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
       // linearLayout.setSystemUiVisibility(View.INVISIBLE);//全屏显示且隐藏状态栏
        servicePhone = (LinearLayout) view.findViewById(R.id.service_phone);
        recordLinear = (LinearLayout) view.findViewById(R.id.browse_recode_linear);
        feedbackLinear = (LinearLayout) view.findViewById(R.id.feedback_linear);
        checkVersion = (LinearLayout) view.findViewById(R.id.version_check);
        username= (TextView) view.findViewById(R.id.username);
        username.setText("点击登录");
    }

    @OnClick({R.id.login_icon, R.id.setting_login, R.id.login_relative1, R.id.login_relative2, R.id.service_phone, R.id.browse_recode_linear
            , R.id.feedback_linear, R.id.version_check, R.id.about_us})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_icon:
                if ("点击登录".equals(username.getText().toString())) {
                    Intent loginIntent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(loginIntent);
                } else {
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/*");//相片类型
                    startActivityForResult(intent, CHOICE_PIC);
                }
                break;
            case R.id.service_phone:
                LogUtils.i("MineFragment:", "-----客服电话");
                showPopupWindow(view);
                break;
            case R.id.negative:
                // 取消弹出窗口
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    setBackgroundAlpha(1.0f);
                }
                break;
            case R.id.browse_recode_linear:
                show();
                break;
            case R.id.version_check:
                Toast.makeText(getContext(), "暂无新版本", Toast.LENGTH_LONG).show();
                break;
            case R.id.feedback_linear:
                Intent feedbackIntent = new Intent();
                feedbackIntent.setClass(getContext(), FeedbackActivity.class);
                startActivity(feedbackIntent);
                break;
            case R.id.call:
                // 拨打客服电话
                String phoneNum = this.getString(R.string.servicePhone);
                phoneNum = "tel:" + phoneNum.replace("-", "");
                Uri uri = Uri.parse(phoneNum);
                Intent intent = new Intent(Intent.ACTION_DIAL, uri);
                startActivity(intent);
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    setBackgroundAlpha(1.0f);
                }
                break;
            case R.id.login_relative1:
                getFragmentManager().beginTransaction()
                        .hide(MainFragment.getInstance())
                        .add(R.id.main_frame, MessCenterFragment.getInstance())
                        .addToBackStack(null)
                        .commit();
                break;
            case R.id.login_relative2:

                break;
            case R.id.setting_login:
                Intent intent1 = new Intent();
                intent1.setClass(getContext(), SetupActivity.class);
                startActivity(intent1);//跳转activity
                break;
            case R.id.about_us:
                getFragmentManager().beginTransaction()
                        .hide(fragment)
                        .add(R.id.main_frame, AboutUsFragment.getInstance())
                        .addToBackStack(null)
                        .commit();
        }
    }

    private void show() {
        Intent intent = new Intent();
        intent.setClass(getContext(), RecodeBrowseActivity.class);
        startActivity(intent);//跳转activity
    }

    public static void setUserName(String userName){
        username.setText(userName);
    }
    public static String getUserName(){
        return username.getText().toString();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            Bitmap bitmap = null;
            LogUtils.i("FeedbackActivity:", "---" + requestCode);
            switch (requestCode) {
                case TAKE_PIC:
//                    Bundle bundle = data.getExtras();
//                    bitmap = (Bitmap) bundle.get("data");
                    break;
                case CHOICE_PIC:
                    Uri picPath = data.getData();
                    Intent intent = new Intent();
                    intent.setAction("com.android.camera.action.CROP");
                    intent.setDataAndType(picPath, "image/*");// mUri是已经选择的图片Uri
                    intent.putExtra("crop", "true");
                    intent.putExtra("aspectX", 1);// 裁剪框比例
                    intent.putExtra("aspectY", 1);
                    intent.putExtra("outputX", loginIcon.getWidth());// 输出图片大小
                    intent.putExtra("outputY", loginIcon.getHeight());
                    intent.putExtra("return-data", true);
                    startActivityForResult(intent, CROP);
                    break;
                case CROP:
                    Bundle bundle = data.getExtras();
                    Bitmap bit = (Bitmap) bundle.get("data");
                    Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), bit, null, null));
                    Glide.with(this)
                            .load(uri)
                            .asBitmap()
                            .transform(new CropCircleTransformation(Glide.get(getActivity()).getBitmapPool()))
                            .into(loginIcon);//直接设置登录图片
                    break;
            }
        }
    }

    /**
     * 弹出式窗口
     *
     * @param view
     */
    private void showPopupWindow(View view) {
        View layout = LayoutInflater.from(getContext()).inflate(R.layout.phone_popup_menu, null);
        if (popupWindow == null) {
            popupWindow = new PopupWindow(layout, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        setBackgroundAlpha(0.5f);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(null);
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
        TextView negativeText = (TextView) layout.findViewById(R.id.negative);
        TextView callText = (TextView) layout.findViewById(R.id.call);
        negativeText.setOnClickListener(this);
        callText.setOnClickListener(this);
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                setBackgroundAlpha(1.0f);
                return false;
            }
        });
    }

    /**
     * 设置屏幕背景透明度
     *
     * @param bgAlpha
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getActivity().getWindow()
                .getAttributes();
        lp.alpha = bgAlpha;
        getActivity().getWindow().setAttributes(lp);
    }

}
